import __config from '../config/env'
const request = (url, data) => {
  let showLoading = true;
  let _url = __config.basePath + url
  console.log('URL========================>'+_url)
  console.log('BODY=======================>'+JSON.stringify(data))
  return new Promise((resolve, reject) => {
    if (showLoading){
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }
    wx.request({
      url: _url,
      method: 'get',
      data: data,
      header: {
        //设置参数内容类型为x-www-form-urlencoded
        'content-type':'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'Authorization':wx.getStorageSync("token")||''
      },
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.code != 200) {
            console.log(res.data)
            wx.showModal({
              title: '提示',
              content: res.data.msg ? res.data.msg : '没有数据' + '',
              showCancel:false,
              success(res) {
                wx.reLaunch({
                  url: '/pages/login/login',
                })
              }
            })
            reject(res.data.msg)
          }
          resolve(res.data)
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            showCancel:false,
            success(res) {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        } else {
          console.log(res)
          wx.showModal({
            title: '提示',
            content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
            showCancel:false,
            success(res) {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        }
      },
      fail(error) {
        console.log(error)
        wx.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          showCancel:false,
          success(res) {
            wx.reLaunch({
              url: '/pages/login/login',
            })
          }
        })
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}
const post = (url, data) => {
  let showLoading = true;
  let _url = __config.basePath + url
  console.log('requestURL=========='+_url)
  console.log('requestData============='+JSON.stringify(data))
  return new Promise((resolve, reject) => {
    if (showLoading){
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }
    wx.request({
      url: _url,
      method: 'POST',
      data: data,
      header: {
        //设置参数内容类型为application/json; charset=UTF-8
        'content-type':'application/json; charset=UTF-8',
        'Accept': 'application/json',
        'Authorization':wx.getStorageSync("token")||''
      },
      success(res) {
        console.log(res)
        if (res.statusCode == 200) {
          if (res.data.code != 200) {
            wx.showModal({
              title: '提示',
              content: res?.data?.msg ? res?.data?.msg : '没有数据' ,
              showCancel:false,
              success(res) {
                wx.reLaunch({
                  url: '/pages/login/login',
                })
              }
            })
            reject(res.data.msg)
          }
          resolve(res.data)
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            showCancel:false,
            success(res) {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        } else {
          console.log(res)
          wx.showModal({
            title: '提示',
            content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
            showCancel:false,
            success(res) {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        }
      },
      fail(error) {
        console.log(error)
        wx.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          showCancel:false,
          success(res) {
            wx.reLaunch({
              url: '/pages/login/login',
            })
          }
        })
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}
const upload = (url, data,filekey,filePath) => {
  let showLoading = true;
  let _url = __config.basePath + url
let params = Object.keys(data).map(function (key) {
        return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
    }).join("&");
  console.log('requestURL=========='+_url)
  console.log('requestData============='+params)
  return new Promise((resolve, reject) => {
    if (showLoading){
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }
    wx.uploadFile({
      url: _url + '?' + params,
      filePath:filePath,
      name:filekey,
      formData: data,
      header: {
        'content-type':'multipart/form-data',
        'Accept': 'application/json',
        'Authorization':wx.getStorageSync("token")||''
      },
      success(res) {
        if (res.statusCode == 200) {
          if(res.data.code == undefined){
            res.data = JSON.parse(res.data);
          }
          if (res.data.code != 200) {
            wx.showModal({
              title: '提示',
              content: res.data.msg ? res.data.msg : '没有数据' + '',
              success() {
                
              },
              complete(){
                if(res.data.code == 401){
                  //session过期，则清除过期session，并重新加载当前页
                  // getApp().globalData.thirdSession = null
                  // wx.reLaunch({
                  //   url: getApp().getCurrentPageUrlWithArgs()
                  // })
                  wx.navigateTo({
                    url: '/pages/login/login',
                  })
                }
              }
            })
            reject(res.data.msg)
          }
          resolve(res.data)
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            success(res) {
            }
          })
          reject()
        } else {
          console.log(res)
          wx.showModal({
            title: '提示',
            content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
            success(res) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        }
      },
      fail(error) {
        console.log(error)
        wx.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          success(res) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        })
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}
module.exports = {
  request,
  login: (data) => {//小程序登录接口
    return post('mlogin', data)
  },
  getUserInfo: () => {//获取用户信息
    return request('getInfo')
  },
  getSchools: () => {//获取学校列表
    return request('getSchools')
  },
  getCourseAndClassByUserid: (userid) => {//获取当前教师班级课程列表
    return request('wx/'+userid)
  },
  getAward: (id) => {//获取当前教师班级课程列表
    return request('wx/getAward',{id})
  },
  saveAward: (data) => {//获取当前教师班级课程列表
    return post('wx/saveAward',data)
  },
  findByStudentStarLogVoByTeacherId: (teacherId,studentName) => {//获取当前教师的授星记录
    return request('wx/findByStudentStarLogVoByTeacherId',{teacherId,studentName})
  },
  listAwardTask: (data) => {//获取任务列表
    return post('wx/listAwardTask',data)
  },
  getAwardTask: (id) => {//获取任务
    return request('wx/getAwardTask',{id})
  },
  getStar: (id) => {//获取星星信息
    return request('wx/getStar',{id})
  },
  getStudents: (departid,batch,teacherid,courseid) => {//获取可以授权的学生
    return request('wx/getStudents',{departid,batch,teacherid,courseid})
  },
  mulSaveAwardTask:(data)=>{
    return post('wx/mulSaveAward',data)
  },
  wxLogin: (code) => {//测试登录
    return get('/login',{code})
  },
}